package com.shanhai.wallpapers.data

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.shanhai.wallpapers.network.remote.PexelsRemoteDataSource
import com.shanhai.wallpapers.network.response.Photo

class PexelsPagingSource(
    private val pexelsRemoteDataSource: PexelsRemoteDataSource,
    private val query: String
) : PagingSource<Int, Photo>() {

    override fun getRefreshKey(state: PagingState<Int, Photo>): Int? {
        return state.anchorPosition
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Photo> {
        val page = params.key ?: PEXELS_INITIAL_PAGE_INDEX
        return try {
            val wallpapersResponse = pexelsRemoteDataSource.getWallpapers(query, page)
            LoadResult.Page(
                data = wallpapersResponse.photos ?: emptyList(),
                prevKey = if (page == PEXELS_INITIAL_PAGE_INDEX) null else page - 1,
                nextKey = if (wallpapersResponse.nextPage.isNullOrBlank()) null else page + 1
            )
        } catch (exception: Exception) {
            LoadResult.Error(exception)
        }
    }

    companion object {
        private const val PEXELS_INITIAL_PAGE_INDEX = 1
    }
}